package uy.com.tsi2G7.superbet.ui;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import uy.com.tsi2G7.superbet.event.Event;
import uy.com.tsi2G7.superbet.event.EventType;
import uy.com.tsi2G7.superbet.event.dao.EventStore;
import uy.com.tsi2G7.superbet.util.SpringContext;


@ApplicationScoped
@ManagedBean(name = "menuPopulator")
public class MenuPopulator {

    private List<MenuDescriptor> groupsList;
    private EventStore eventStore;
    
    
    
    public MenuPopulator() {
	}
    
    public void reset() {
		groupsList=null;
	}
    
    public synchronized List<MenuDescriptor> getGroupsList() {
    	if(groupsList!=null)
    		return groupsList;
    	groupsList=new ArrayList<MenuDescriptor>();
    	List<EventType> eventTypes = getEventStore().getAllEventTypes();
    	List<Event> events = getEventStore().getAllEvents();
		for (EventType type : eventTypes) {
			MenuDescriptor eventTypeDescriptor=new MenuDescriptor();
			eventTypeDescriptor.setId(type.getId());
			eventTypeDescriptor.setName(type.getName());
			for (Event event : events) {
				if(event.getEventTypeId().longValue()==type.getId().longValue()){
					MenuDescriptor eventDescriptor=new MenuDescriptor();
					eventDescriptor.setId(event.getId());
					eventDescriptor.setName(event.getName());
					eventTypeDescriptor.getChildren().add(eventDescriptor);
				}
			}
			groupsList.add(eventTypeDescriptor);
		}
		
    	return groupsList;
    }
    
    public EventStore getEventStore() {
    	if(eventStore==null)
    		eventStore=(EventStore) SpringContext.getApplicationContext().getBean("eventStore");
		return eventStore;
	}

}
